<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/limh/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/limh/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/limh/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/limh/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/limh/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/limh/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/limh/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="教程,">










<meta name="description" content="我们前边学串口通信的时候，比较注重的是串口底层时序上的操作过程，所以例程都是简单的收发字符或者字符串。在实际应用中，往往串口还要和电脑上的上位机软件进行交互，实现电脑软件发送不同的指令，单片机对应执行不同操作的功能，这就要求我们组织一个比较合理的通信机制和逻辑关系，用来实现我们想要的结果。 本节所提供程序的功能是，通过电脑串口调试助手下发三个不同的命令，第一条指令：buzz on 可以让蜂鸣器响；">
<meta name="keywords" content="教程">
<meta property="og:type" content="article">
<meta property="og:title" content="13.5、串口通信原理和控制程序">
<meta property="og:url" content="https://tdnr.gitee.io/limh/2014/12/01/mcu089/index.html">
<meta property="og:site_name" content="土逗牛肉">
<meta property="og:description" content="我们前边学串口通信的时候，比较注重的是串口底层时序上的操作过程，所以例程都是简单的收发字符或者字符串。在实际应用中，往往串口还要和电脑上的上位机软件进行交互，实现电脑软件发送不同的指令，单片机对应执行不同操作的功能，这就要求我们组织一个比较合理的通信机制和逻辑关系，用来实现我们想要的结果。 本节所提供程序的功能是，通过电脑串口调试助手下发三个不同的命令，第一条指令：buzz on 可以让蜂鸣器响；">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-01-28T12:58:25.514Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="13.5、串口通信原理和控制程序">
<meta name="twitter:description" content="我们前边学串口通信的时候，比较注重的是串口底层时序上的操作过程，所以例程都是简单的收发字符或者字符串。在实际应用中，往往串口还要和电脑上的上位机软件进行交互，实现电脑软件发送不同的指令，单片机对应执行不同操作的功能，这就要求我们组织一个比较合理的通信机制和逻辑关系，用来实现我们想要的结果。 本节所提供程序的功能是，通过电脑串口调试助手下发三个不同的命令，第一条指令：buzz on 可以让蜂鸣器响；">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/limh/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://tdnr.gitee.io/limh/2014/12/01/mcu089/">





  <title>13.5、串口通信原理和控制程序 | 土逗牛肉</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans ">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/limh/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">土逗牛肉</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/limh/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/limh/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/limh/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/limh/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/limh/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://tdnr.gitee.io/limh/limh/2014/12/01/mcu089/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="土逗牛肉">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/limh/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="土逗牛肉">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">13.5、串口通信原理和控制程序</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2014-12-01T20:37:12+08:00">
                2014-12-01
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/limh/categories/单片机教程/" itemprop="url" rel="index">
                    <span itemprop="name">单片机教程</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>我们前边学串口通信的时候，比较注重的是串口底层时序上的操作过程，所以例程都是简单的收发字符或者字符串。在实际应用中，往往串口还要和电脑上的上位机软件进行交互，实现电脑软件发送不同的指令，单片机对应执行不同操作的功能，这就要求我们组织一个比较合理的通信机制和逻辑关系，用来实现我们想要的结果。</p>
<p>本节所提供程序的功能是，通过电脑串口调试助手下发三个不同的命令，第一条指令：buzz on 可以让蜂鸣器响；第二条指令：buzz off 可以让蜂鸣器不响；第三条指令：showstr ，这个命令空格后边，可以添加任何字符串，让后边的字符串在 1602 液晶上显示出来，同时不管发送什么命令，单片机收到后把命令原封不动的再通过串口发送给电脑，以表示“我收到了„„你可以检查下对不对”。这样的感觉是不是更像是一个小项目了呢？</p>
<p>对于串口通信部分来说，单片机给电脑发字符串好说，有多大的数组，我们就发送多少个字节即可，但是单片机接收数据，接收多少个才应该是一帧完整的数据呢？数据接收起始头在哪里，结束在哪里？这些我们在接收到数据前都是无从得知的。那怎么办呢？</p>
<p>我们的编程思路基于这样一种通常的事实：当需要发送一帧（多个字节）数据时，这些数据都是连续不断的发送的，即发送完一个字节后会紧接着发送下一个字节，期间没有间隔或间隔很短，而当这一帧数据都发送完毕后，就会间隔很长一段时间（相对于连续发送时的间隔来讲）不再发送数据，也就是通信总线上会空闲一段较长的时间。于是我们就建立这样一种程序机制：设置一个软件的总线空闲定时器，这个定时器在有数据传输时（从单片机接收角度来说就是接收到数据时）清零，而在总线空闲时（也就是没有接收到数据时）时累加，当它累加到一定时间（例程里是 30ms）后，我们就可以认定一帧完整的数据已经传输完毕了，于是告诉其它程序可以来处理数据了，本次的数据处理完后就恢复到初始状态，再准备下一次的接收。那么这个用于判定一帧结束的空闲时间取多少合适呢？它取决于多个条件，并没有一个固定值，我们这里介绍几个需要考虑的原则：第一，这个时间必须大于波特率周期，很明显我们的单片机接收中断产生是在一个字节接收完毕后，也就是一个时刻点，而其接收过程我们的程序是无从知晓的，因此在至少一个波特率周期内你绝不能认为空闲已经时间达到了。第二，要考虑发送方的系统延时，因为不是所有的发送方都能让数据严格无间隔的发送，因为软件响应、关中断、系统临界区等等操作都会引起延时，所以还得再附加几个到十几个 ms 的时间。我们选取的 30ms 是一个折中的经验值，它能适应大部分的波特率（大于1200）和大部分的系统延时（PC 机或其它单片机系统）情况。</p>
<p>我先把这个程序最重要的 UART.c 文件中的程序贴出来，一点点给大家解析，这个是实际项目开发常用的用法，大家一定要认真弄明白。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br></pre></td><td class="code"><pre><span class="line">/*****************************Uart.c 文件程序源代码*****************************/</span><br><span class="line">#include &lt;reg52.h&gt;</span><br><span class="line">bit flagFrame = 0; //帧接收完成标志，即接收到一帧新数据</span><br><span class="line">bit flagTxd = 0; //单字节发送完成标志，用来替代 TXD 中断标志位</span><br><span class="line">unsigned char cntRxd = 0; //接收字节计数器</span><br><span class="line">unsigned char pdata bufRxd[64]; //接收字节缓冲区</span><br><span class="line">extern void UartAction(unsigned char *buf, unsigned char len);</span><br><span class="line">/* 串口配置函数，baud-通信波特率 */</span><br><span class="line">void ConfigUART(unsigned int baud)&#123;</span><br><span class="line">    SCON = 0x50; //配置串口为模式 1</span><br><span class="line">    TMOD &amp;= 0x0F; //清零 T1 的控制位</span><br><span class="line">    TMOD |= 0x20; //配置 T1 为模式 2</span><br><span class="line">    TH1 = 256 - (11059200/12/32)/baud; //计算 T1 重载值</span><br><span class="line">    TL1 = TH1; //初值等于重载值</span><br><span class="line">    ET1 = 0; //禁止 T1 中断</span><br><span class="line">    ES = 1; //使能串口中断</span><br><span class="line">    TR1 = 1; //启动 T1</span><br><span class="line">&#125;</span><br><span class="line">/* 串口数据写入，即串口发送函数，buf-待发送数据的指针，len-指定的发送长度 */</span><br><span class="line">void UartWrite(unsigned char *buf, unsigned char len)&#123;</span><br><span class="line">    while (len--)&#123; //循环发送所有字节</span><br><span class="line">        flagTxd = 0; //清零发送标志</span><br><span class="line">        SBUF = *buf++; //发送一个字节数据</span><br><span class="line">        while (!flagTxd); //等待该字节发送完成</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">/* 串口数据读取函数，buf-接收指针，len-指定的读取长度，返回值-实际读到的长度 */</span><br><span class="line">unsigned char UartRead(unsigned char *buf, unsigned char len)&#123;</span><br><span class="line">    unsigned char i;</span><br><span class="line">    //指定读取长度大于实际接收到的数据长度时，</span><br><span class="line">    //读取长度设置为实际接收到的数据长度</span><br><span class="line">    if (len &gt; cntRxd)&#123;</span><br><span class="line">        len = cntRxd;</span><br><span class="line">    &#125;</span><br><span class="line">    for (i=0; i&lt;len; i++)&#123; //拷贝接收到的数据到接收指针上</span><br><span class="line">        *buf++ = bufRxd[i];</span><br><span class="line">    &#125;</span><br><span class="line">    cntRxd = 0; //接收计数器清零</span><br><span class="line">    return len; //返回实际读取长度</span><br><span class="line">&#125;</span><br><span class="line">/* 串口接收监控，由空闲时间判定帧结束，需在定时中断中调用，ms-定时间隔 */</span><br><span class="line">void UartRxMonitor(unsigned char ms)&#123;</span><br><span class="line">    static unsigned char cntbkp = 0;</span><br><span class="line">    static unsigned char idletmr = 0;</span><br><span class="line">   </span><br><span class="line">    if (cntRxd &gt; 0)&#123; //接收计数器大于零时，监控总线空闲时间</span><br><span class="line">        if (cntbkp != cntRxd)&#123; //接收计数器改变，即刚接收到数据时，清零空闲计时</span><br><span class="line">            cntbkp = cntRxd;</span><br><span class="line">            idletmr = 0;</span><br><span class="line">        &#125;else&#123; //接收计数器未改变，即总线空闲时，累积空闲时间</span><br><span class="line">            if (idletmr &lt; 30)&#123; //空闲计时小于 30ms 时，持续累加</span><br><span class="line">                idletmr += ms;</span><br><span class="line">                if (idletmr &gt;= 30)&#123; //空闲时间达到 30ms 时，即判定为一帧接收完毕</span><br><span class="line">                    flagFrame = 1; //设置帧接收完成标志</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;else&#123;</span><br><span class="line">        cntbkp = 0;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">/* 串口驱动函数，监测数据帧的接收，调度功能函数，需在主循环中调用 */</span><br><span class="line">void UartDriver()&#123;</span><br><span class="line">    unsigned char len;</span><br><span class="line">    unsigned char pdata buf[40];</span><br><span class="line">    if (flagFrame)&#123; //有命令到达时，读取处理该命令</span><br><span class="line">        flagFrame = 0;</span><br><span class="line">        len = UartRead(buf, sizeof(buf)); //将接收到的命令读取到缓冲区中</span><br><span class="line">        UartAction(buf, len); //传递数据帧，调用动作执行函数</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">/* 串口中断服务函数 */</span><br><span class="line">void InterruptUART() interrupt 4&#123;</span><br><span class="line">    if (RI)&#123; //接收到新字节</span><br><span class="line">        RI = 0; //清零接收中断标志位</span><br><span class="line">        //接收缓冲区尚未用完时，保存接收字节，并递增计数器</span><br><span class="line">        if (cntRxd &lt; sizeof(bufRxd))&#123;&#123;</span><br><span class="line">            bufRxd[cntRxd++] = SBUF;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    if (TI)&#123; //字节发送完毕</span><br><span class="line">        TI = 0; //清零发送中断标志位</span><br><span class="line">        flagTxd = 1; //设置字节发送完成标志</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>大家可以对照注释和前面的讲解分析下这个 Uart.c 文件，在这里指出其中的两个要点希望大家多注意下。</p>
<p>1、接收数据的处理，在串口中断中，将接收到的字节都存入缓冲区 bufRxd 中，同时利用另外的定时器中断通过间隔调用 UartRxMonitor 来监控一帧数据是否接收完毕，判定的原则就是我们前面介绍的空闲时间，当判定一帧数据结束完毕时，设置 flagFrame 标志，主循环中可以通过调用 UartDriver 来检测该标志，并处理接收到的数据。当要处理接收到的数据时，先通过串口读取函数 UartRead 把接收缓冲区 bufRxd 中的数据读取出来，然后再对读到的数据进行判断处理。也许你会说，既然数据都已经接收到 bufRxd 中了，那我直接在这里面用不就行了嘛，何必还得再拷贝到另一个地方去呢？我们设计这种双缓冲的机制，主要是为了提高串口接收到响应效率：首先如果你在 bufRxd 中处理数据，那么这时侯就不能再接收任何数据，因为新接收的数据会破坏原来的数据，造成其不完整和混乱；其次，这个处理过程可能会耗费较长的时间，比如说上位机现在就给你发来一个延时显示的命令，那么在这个延时的过程中你都无法去接收新的命令，在上位机看来就是你暂时失去响应了。而使用这种双缓冲机制就可以大大改善这个问题，因为数据拷贝所需的时间是相当短的，而只要拷贝出去后，bufRxd 就可以马上准备去接收新数据了。</p>
<p>2、串口数据写入函数 UartWrite，它把数据指针 buf 指向的数据块连续的由串口发送出去。虽然我们的串口程序启用了中断，但这里的发送功能却没有在中断中完成，而是仍然靠查询发送中断标志 flagTxd（因中断函数内必须清零 TI，否则中断会重复进入执行，所以另置了一个 flagTxd 来代替 TI）来完成，当然也可以采用先把发送数据拷贝到一个缓冲区中，然后再在中断中发缓冲区数据发送出去的方式，但这样一是要耗费额外的内存，二是使程序更复杂。这里也还是想告诉大家，简单方式可以解决的问题就不要搞得更复杂。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br></pre></td><td class="code"><pre><span class="line">/*****************************main.c 文件程序源代码******************************/</span><br><span class="line">#include &lt;reg52.h&gt;</span><br><span class="line">sbit BUZZ = P1^6; //蜂鸣器控制引脚</span><br><span class="line">bit flagBuzzOn = 0; //蜂鸣器启动标志</span><br><span class="line">unsigned char T0RH = 0; //T0 重载值的高字节</span><br><span class="line">unsigned char T0RL = 0; //T0 重载值的低字节</span><br><span class="line">void ConfigTimer0(unsigned int ms);</span><br><span class="line">extern void UartDriver();</span><br><span class="line">extern void ConfigUART(unsigned int baud);</span><br><span class="line">extern void UartRxMonitor(unsigned char ms);</span><br><span class="line">extern void UartWrite(unsigned char *buf, unsigned char len);</span><br><span class="line">extern void InitLcd1602();</span><br><span class="line">extern void LcdShowStr(unsigned char x, unsigned char y, unsigned char *str);</span><br><span class="line">extern void LcdAreaClear(unsigned char x, unsigned char y, unsigned char len);</span><br><span class="line">void main()&#123;</span><br><span class="line">    EA = 1; //开总中断</span><br><span class="line">    ConfigTimer0(1); //配置 T0 定时 1ms</span><br><span class="line">    ConfigUART(9600); //配置波特率为 9600</span><br><span class="line">    InitLcd1602(); //初始化液晶</span><br><span class="line">    while (1)&#123;</span><br><span class="line">        UartDriver(); //调用串口驱动</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">/* 内存比较函数，比较两个指针所指向的内存数据是否相同，</span><br><span class="line">ptr1-待比较指针 1，ptr2-待比较指针 2，len-待比较长度</span><br><span class="line">返回值-两段内存数据完全相同时返回 1，不同返回 0 */</span><br><span class="line">bit CmpMemory(unsigned char *ptr1, unsigned char *ptr2, unsigned char len)&#123;</span><br><span class="line">    while (len--)&#123;</span><br><span class="line">        if (*ptr1++ != *ptr2++)&#123; //遇到不相等数据时即刻返回 0</span><br><span class="line">            return 0;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    return 1; //比较完全部长度数据都相等则返回 1</span><br><span class="line">&#125;</span><br><span class="line">/* 串口动作函数，根据接收到的命令帧执行响应的动作</span><br><span class="line">buf-接收到的命令帧指针，len-命令帧长度 */</span><br><span class="line">void UartAction(unsigned char *buf, unsigned char len)&#123;</span><br><span class="line">    unsigned char i;</span><br><span class="line">    unsigned char code cmd0[] = &quot;buzz on&quot;; //开蜂鸣器命令</span><br><span class="line">    unsigned char code cmd1[] = &quot;buzz off&quot;; //关蜂鸣器命令</span><br><span class="line">    unsigned char code cmd2[] = &quot;showstr &quot;; //字符串显示命令</span><br><span class="line">    unsigned char code cmdLen[] = &#123; //命令长度汇总表</span><br><span class="line">        sizeof(cmd0)-1, sizeof(cmd1)-1, sizeof(cmd2)-1,</span><br><span class="line">    &#125;;</span><br><span class="line">   </span><br><span class="line">    unsigned char code *cmdPtr[] = &#123; //命令指针汇总表</span><br><span class="line">        &amp;cmd0[0], &amp;cmd1[0], &amp;cmd2[0],</span><br><span class="line">    &#125;;</span><br><span class="line">    for (i=0; i&lt;sizeof(cmdLen); i++)&#123; //遍历命令列表，查找相同命令</span><br><span class="line">        if (len &gt;= cmdLen[i])&#123; //首先接收到的数据长度要不小于命令长度</span><br><span class="line">            if (CmpMemory(buf, cmdPtr[i], cmdLen[i]))&#123; //比较相同时退出循环</span><br><span class="line">                break;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    switch (i)&#123; //循环退出时 i 的值即是当前命令的索引值</span><br><span class="line">        case 0:</span><br><span class="line">            flagBuzzOn = 1; //开启蜂鸣器</span><br><span class="line">            break;</span><br><span class="line">        case 1:</span><br><span class="line">            flagBuzzOn = 0; //关闭蜂鸣器</span><br><span class="line">            break;</span><br><span class="line">        case 2:</span><br><span class="line">            buf[len] = &apos;\0&apos;; //为接收到的字符串添加结束符</span><br><span class="line">            LcdShowStr(0, 0, buf+cmdLen[2]); //显示命令后的字符串</span><br><span class="line">            i = len - cmdLen[2]; //计算有效字符个数</span><br><span class="line">            if (i &lt; 16)&#123; //有效字符少于 16 时，清除液晶上的后续字符位</span><br><span class="line">                LcdAreaClear(i, 0, 16-i);</span><br><span class="line">            &#125;</span><br><span class="line">            break;</span><br><span class="line">        default: //未找到相符命令时，给上机发送“错误命令”的提示</span><br><span class="line">            UartWrite(&quot;bad command.\r\n&quot;, sizeof(&quot;bad command.\r\n&quot;)-1);</span><br><span class="line">            return;</span><br><span class="line">    &#125;</span><br><span class="line">    buf[len++] = &apos;\r&apos;; //有效命令被执行后，在原命令帧之后添加</span><br><span class="line">    buf[len++] = &apos;\n&apos;; //回车换行符后返回给上位机，表示已执行</span><br><span class="line">    UartWrite(buf, len);</span><br><span class="line">&#125;</span><br><span class="line">/* 配置并启动 T0，ms-T0 定时时间 */</span><br><span class="line">void ConfigTimer0(unsigned int ms)&#123;</span><br><span class="line">    unsigned long tmp; //临时变量</span><br><span class="line">    tmp = 11059200 / 12; //定时器计数频率</span><br><span class="line">    tmp = (tmp * ms) / 1000; //计算所需的计数值</span><br><span class="line">    tmp = 65536 - tmp; //计算定时器重载值</span><br><span class="line">    tmp = tmp + 33; //补偿中断响应延时造成的误差</span><br><span class="line">    T0RH = (unsigned char)(tmp&gt;&gt;8); //定时器重载值拆分为高低字节</span><br><span class="line">    T0RL = (unsigned char)tmp;</span><br><span class="line">    TMOD &amp;= 0xF0; //清零 T0 的控制位</span><br><span class="line">    TMOD |= 0x01; //配置 T0 为模式 1</span><br><span class="line">    TH0 = T0RH; //加载 T0 重载值</span><br><span class="line">    TL0 = T0RL;</span><br><span class="line">    ET0 = 1; //使能 T0 中断</span><br><span class="line">    TR0 = 1; //启动 T0</span><br><span class="line">&#125;</span><br><span class="line">/* T0 中断服务函数，执行串口接收监控和蜂鸣器驱动 */</span><br><span class="line">void InterruptTimer0() interrupt 1&#123;</span><br><span class="line">    TH0 = T0RH; //重新加载重载值</span><br><span class="line">    TL0 = T0RL;</span><br><span class="line">    if (flagBuzzOn)&#123; //执行蜂鸣器鸣叫或关闭</span><br><span class="line">        BUZZ = ~BUZZ;</span><br><span class="line">    &#125;else&#123;</span><br><span class="line">        BUZZ = 1;</span><br><span class="line">    &#125;</span><br><span class="line">    UartRxMonitor(1); //串口接收监控</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>main 函数和主循环的结构我们已经做过很多了，就不多说了，这里重点把串口接收数据的具体解析方法给大家分析一下，这种用法具有很强的普遍性，掌握并灵活运用它可以使你将来的开发工作事半功倍。</p>
<p>首先来看 CmpMemory 函数，这个函数很简单，就是比较两段内存数据，通常都是数组中的数据，函数接收两段数据的指针，然后逐个字节比较——if (<em>ptr1++ != </em>ptr2++)，这行代码既完成了两个指针指向的数据的比较，又在比较完后把两个指针都各自+1，从这里是不是也能领略到一点 C 语言的简洁高效的魅力呢。这个函数的用处自然就是用来比较我们接收到的数据和事先放在程序里的命令字符串是否相同，从而找出相符的命令了。</p>
<p>接下来是 UartAction 函数对接收数据的解析和处理方法，先把接收的数据与所支持的命令字符串逐条比较，这个比较中首先要确保接收的长度大于命令字符串的长度，然后再用上述的 CmpMemory 函数逐字节比较，如果比较相同就立即退出循环，不同则继续对比下一条命令。当找到相符的命令字符串时，最终 i 的值就是该命令在其列表中的索引位置，当遍历完命令列表都没有找到相符的命令时，最终 i 的值将等于命令总数，那么接下来就用 switch语句根据 i 的值来执行具体的动作，这个就不需要再详细说明了。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br></pre></td><td class="code"><pre><span class="line">/***************************Lcd1602.c 文件程序源代码*****************************/</span><br><span class="line">#include &lt;reg52.h&gt;</span><br><span class="line">#define LCD1602_DB P0</span><br><span class="line">sbit LCD1602_RS = P1^0;</span><br><span class="line">sbit LCD1602_RW = P1^1;</span><br><span class="line">sbit LCD1602_E = P1^5;</span><br><span class="line">/* 等待液晶准备好 */</span><br><span class="line">void LcdWaitReady()&#123;</span><br><span class="line">    unsigned char sta;</span><br><span class="line">    LCD1602_DB = 0xFF;</span><br><span class="line">    LCD1602_RS = 0;</span><br><span class="line">    LCD1602_RW = 1;</span><br><span class="line">    do &#123;</span><br><span class="line">        LCD1602_E = 1;</span><br><span class="line">        sta = LCD1602_DB; //读取状态字</span><br><span class="line">        LCD1602_E = 0;</span><br><span class="line">    &#125; while (sta &amp; 0x80); //bit7 等于 1 表示液晶正忙，重复检测直到其等于 0 为止</span><br><span class="line">&#125;</span><br><span class="line">/* 向 LCD1602 液晶写入一字节命令，cmd-待写入命令值 */</span><br><span class="line">void LcdWriteCmd(unsigned char cmd)&#123;</span><br><span class="line">    LcdWaitReady();</span><br><span class="line">    LCD1602_RS = 0;</span><br><span class="line">    LCD1602_RW = 0;</span><br><span class="line">    LCD1602_DB = cmd;</span><br><span class="line">    LCD1602_E = 1;</span><br><span class="line">    LCD1602_E = 0;</span><br><span class="line">&#125;</span><br><span class="line">/* 向 LCD1602 液晶写入一字节数据，dat-待写入数据值 */</span><br><span class="line">void LcdWriteDat(unsigned char dat)&#123;</span><br><span class="line">    LcdWaitReady();</span><br><span class="line">    LCD1602_RS = 1;</span><br><span class="line">    LCD1602_RW = 0;</span><br><span class="line">    LCD1602_DB = dat;</span><br><span class="line">    LCD1602_E = 1;</span><br><span class="line">    LCD1602_E = 0;</span><br><span class="line">&#125;</span><br><span class="line">/* 设置显示 RAM 起始地址，亦即光标位置，(x,y)-对应屏幕上的字符坐标 */</span><br><span class="line">void LcdSetCursor(unsigned char x, unsigned char y)&#123;</span><br><span class="line">    unsigned char addr;</span><br><span class="line">    if (y == 0)&#123; //由输入的屏幕坐标计算显示 RAM 的地址</span><br><span class="line">        addr = 0x00 + x; //第一行字符地址从 0x00 起始</span><br><span class="line">    &#125;else&#123;</span><br><span class="line">        addr = 0x40 + x; //第二行字符地址从 0x40 起始</span><br><span class="line">    &#125;</span><br><span class="line">    LcdWriteCmd(addr | 0x80); //设置 RAM 地址</span><br><span class="line">&#125;</span><br><span class="line">/* 在液晶上显示字符串，(x,y)-对应屏幕上的起始坐标，str-字符串指针 */</span><br><span class="line">void LcdShowStr(unsigned char x, unsigned char y, unsigned char *str)&#123;</span><br><span class="line">    LcdSetCursor(x, y); //设置起始地址</span><br><span class="line">    while (*str != &apos;\0&apos;)&#123; //连续写入字符串数据，直到检测到结束符</span><br><span class="line">        LcdWriteDat(*str++);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">/* 区域清除，清除从(x,y)坐标起始的 len 个字符位 */</span><br><span class="line">void LcdAreaClear(unsigned char x, unsigned char y, unsigned char len)&#123;</span><br><span class="line">    LcdSetCursor(x, y); //设置起始地址</span><br><span class="line">    while (len--)&#123; //连续写入空格</span><br><span class="line">        LcdWriteDat(&apos; &apos;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">/* 初始化 1602 液晶 */</span><br><span class="line">void InitLcd1602()&#123;</span><br><span class="line">    LcdWriteCmd(0x38); //16*2 显示，5*7 点阵，8 位数据接口</span><br><span class="line">    LcdWriteCmd(0x0C); //显示器开，光标关闭</span><br><span class="line">    LcdWriteCmd(0x06); //文字不动，地址自动+1</span><br><span class="line">    LcdWriteCmd(0x01); //清屏</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>液晶文件与上一个例程的液晶文件基本是一样的，唯一的区别是删掉了一个本例中用不到的全屏清屏函数，其实留着这个函数也没关系，只是 Keil 会提示一个警告，告诉你有未被调用的函数而已，可以不理会它。</p>
<p>经过这几个多文件工程的练习后，大家是否发现，在采用多文件模块化编程后，不光是某些函数，甚至整个 c 文件，如有需要，我们都可以直接复制到其它的新工程中使用，非常方便功能程序的移植，这样随着实践积累的增加，你会发现工作效率变得越来越高了。</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/limh/tags/教程/" rel="tag"># 教程</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/limh/2014/12/01/mcu088/" rel="next" title="13.4、单片机计算器实例">
                <i class="fa fa-chevron-left"></i> 13.4、单片机计算器实例
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/limh/2014/12/01/mcu090/" rel="prev" title="14.1、单片机I2C时序介绍">
                14.1、单片机I2C时序介绍 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="SOHUCS"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/limh/images/avatar.jpg" alt="土逗牛肉">
            
              <p class="site-author-name" itemprop="name">土逗牛肉</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/limh/archives/">
              
                  <span class="site-state-item-count">255</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/limh/categories/index.html">
                  <span class="site-state-item-count">8</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/limh/tags/index.html">
                  <span class="site-state-item-count">7</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/limhGeek" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:1591054297@qq.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.jianshu.com/u/f73b243e7cc9" target="_blank" title="简书">
                      
                        <i class="fa fa-fw fa-user-circle-o"></i>简书</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">土逗牛肉</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
	var str = GetUrlParam('height');
    if (str === '0'){
		document.getElementById('header').style.display = 'none';
		document.getElementById('comments').style.display = 'none';
		document.getElementById('footer').style.display = 'none';
		document.getElementsByClassName('post-footer').item(0).style.display = 'none'
	}
	
    function GetUrlParam(paraName) {
        var url = document.location.toString();
        var arrObj = url.split("?");

        if (arrObj.length > 1) {
            var arrPara = arrObj[1].split("&");
            var arr;

            for (var i = 0; i < arrPara.length; i++) {
                 arr = arrPara[i].split("=");

                if (arr != null && arr[0] === paraName) {
                    return arr[1];
                }
            }
            return "";
        } else {
            return "";
        }
    }
</script>









  












  
  
    <script type="text/javascript" src="/limh/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/limh/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/limh/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/limh/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/limh/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/limh/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/limh/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/limh/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/limh/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/limh/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/limh/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/limh/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/limh/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
